// pages/purchase/purchase.js
var httpUtil = require('../../utils/httpUtil.js');
var util = require('../../utils/util.js');
var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    flag:true,
    flag1: true,
    animationData: {},
    express:[
      {
        company:'免邮费',
        urlImg:'../images/sel-n.png',
        urlSelImg: '../images/apt.png',
        money:0
      }
    ],
    curIdx:0,
    goods:{},
    expressMoney:0.0,
    num:1,
    money:0.0,
    moneyTotal:0.0,
    company:"免邮费",
    companyMoney:24,
    specification:'',
    userName:'',
    userPhone:'',
    userAddress:'',
    userInfo: {},
    setMeal:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that=this;
    var pages = getCurrentPages();
    var userInfo = util.getKey("userInfo");

    var prevPage = pages[pages.length - 2];  //上一个页面
    console.log(prevPage.data.setMeal[prevPage.data.clickId]);
    that.setData({
      goods: prevPage.data.goods,
      money: prevPage.data.money,
      moneyTotal: prevPage.data.money,
      specification: prevPage.data.setMeal[prevPage.data.clickId],
      userInfo: userInfo
    })
    httpUtil.getHttp("/goods_travel/get/logistics?goodsId=" + prevPage.data.goods.id, {}, function (res) {
      var express = [];
      if (res != null && res.length != 0) {
        for (var i = 0; i < res.length; i++) {
          express.push({
            company: res[i].name,
            urlImg: '../images/sel-n.png',
            urlSelImg: '../images/apt.png',
            money: parseFloat(res[i].money)
          })
        }
      }
      if (express.length != 0) {
        that.setData({
          express: express,
          companyMoney: express[0].money,
          company: express[0].name
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  costShow: function (e) {
    // 用that取代this，防止不必要的情况发生
    var that = this;
    // 创建一个动画实例
    var animation = wx.createAnimation({
      // 动画持续时间
      duration: 500,
      // 定义动画效果，当前是匀速
      timingFunction: 'linear'
    })
    // 将该变量赋值给当前动画
    that.animation = animation
    // 先在y轴偏移，然后用step()完成一个动画
    animation.translateY(200).step()
    // 用setData改变当前动画
    
    that.setData({
      // 通过export()方法导出数据
      animationData: animation.export(),
      // 改变view里面的Wx：if
      flag: !that.data.flag
    })
    // 设置setTimeout来改变y轴偏移量，实现有感觉的滑动
    setTimeout(function () {
      animation.translateY(0).step()
      that.setData({
        animationData: animation.export()
      })
    }, 200)
  },
  costHide:function(e){
    var that = this;
    that.setData({
      flag:true
    })
  },
  selExpress:function(e){
    var that=this;
    that.setData({
      curIdx: e.currentTarget.dataset.index,
      flag1:true,
      company: that.data.express[e.currentTarget.dataset.index].company,
      companyMoney: that.data.express[e.currentTarget.dataset.index].money
    })

  },
  selPurchase:function(e){
    // 用that取代this，防止不必要的情况发生
    var that = this;
    // 创建一个动画实例
    var animation = wx.createAnimation({
      // 动画持续时间
      duration: 500,
      // 定义动画效果，当前是匀速
      timingFunction: 'linear'
    })
    // 将该变量赋值给当前动画
    that.animation = animation
    // 先在y轴偏移，然后用step()完成一个动画
    animation.translateY(200).step()
    // 用setData改变当前动画

    that.setData({
      // 通过export()方法导出数据
      animationData: animation.export(),
      // 改变view里面的Wx：if
      flag1:false
    })
    // 设置setTimeout来改变y轴偏移量，实现有感觉的滑动
    setTimeout(function () {
      animation.translateY(0).step()
      that.setData({
        animationData: animation.export()
      })
    }, 200)
  },
  hidePurchase:function(){
    var that = this;
    that.setData({
      flag1: true
    })
  },
  add:function(){
    var that=this;
    if(that.data.num>0){
     that.setData({
       num:that.data.num+1,
       moneyTotal: that.data.money * (that.data.num+1)
     }) 
    }
  },
  del: function () {
    var that = this;
    if (that.data.num >1) {
      that.setData({
        num: that.data.num - 1,
        moneyTotal: that.data.money * (that.data.num - 1)

      })
    }
  },setUserName:function(e){
    var val = e.detail.value;
    this.setData({
      userName: val
    })
  }, setUserPhone: function (e) {
    var val = e.detail.value;
    this.setData({
      userPhone: val
    })
  }, setUserAddress: function (e) {
    var val = e.detail.value;
    this.setData({
      userAddress: val
    })
  }, save:function(){
    var that=this;
    var userName = that.data.userName;
    var userPhone = that.data.userPhone;
    var userAddress = that.data.userAddress;
    console.log(userPhone);
    console.log(userAddress);
    console.log(userName);
    var userInfo = that.data.userInfo;

    if (userName==''){
      wx.showToast({
        title: '请填写姓名',
        icon: 'loading',
        duration: 1000,
        mask: true
      })
      return;
    }
    if (userPhone == '') {
      wx.showToast({
        title: '请填写电话',
        icon: 'loading',
        duration: 1000,
        mask: true
      })
      return;
    }
    if (userAddress == '') {
      wx.showToast({
        title: '请填写地址',
        icon: 'loading',
        duration: 1000,
        mask: true
      })
      return; 
    }
    var address = { userId: userInfo.id, name: userName, phone: userPhone, text: userAddress}

    httpUtil.postHttp("/order/pay/visa?userId=" + userInfo.id + "&goodsLogistics="+that.data.company+ "&freightMoney=" + that.data.companyMoney+"&goodsId=" + that.data.goods.id + "&specificationId=" + that.data.specification.id + "&num=" + that.data.num 
      , address, function (res) {
        wx.requestPayment({
          'timeStamp': res.data.timeStamp,
          'nonceStr': res.data.nonceStr,
          'package': res.data.package,
          'signType': res.data.signType,
          'paySign': res.data.paySign,
          'success': function (res) {
            wx.showToast({
              title: "支付成功",
              icon: 'loading',
              duration: 500
            });
            wx.navigateTo({
              url: '../paySuccess/paySuccess'
            })
          },
          'fail': function (res) {
            console.log(res);
            wx.showToast({
              title: "支付失败",
              icon: 'loading',
              duration: 500
            });

          }
        })
      })
  },  //用户选择收货地址
  chooseAddress: function () {
    var that = this;
    if (wx.chooseAddress && that.data.userAddress=='') {
      wx.chooseAddress({
        success: function (res) {
          console.log(JSON.stringify(res));
          console.log(res);
          that.setData({
            userAddress: res.provinceName + res.cityName + res.countyName + res.detailInfo,
            userName: res.userName,
            userPhone: res.telNumber
          })
         
        },
        fail: function (err) {
          console.log(JSON.stringify(err));
          console.info("收货地址授权失败");
          wx.showToast({
            title: '授权失败，您将无法进行下单支付;重新授权请删除小程序后再次进入',
            icon: 'success',
            duration: 20000
          })
        }
      })
    } else {
      console.log('当前微信版本不支持chooseAddress');
    }
  },
})